package com.Android.Intr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EventActivity extends ListActivity {
	static ArrayList<EventEntry> events;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  final SharedPreferences settings = getSharedPreferences("PREF", 0);
	  String username = settings.getString("Username", "");
	  String[] listOfEvents = null;
	  try {
		  listOfEvents = requestEventsFromServer(username);
		  setListAdapter(new ArrayAdapter<String>(this, R.layout.eventitem, listOfEvents));
	  
		  ListView lv = getListView();
		  lv.setTextFilterEnabled(true);

		  /*lv.setOnItemClickListener(new OnItemClickListener() {
	    	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	      	Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
	    	}
	  	});*/
	  
		  lv.setOnItemClickListener(new OnItemClickListener() {
			  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				  Intent toEvent = new Intent(EventActivity.this, EventViewActivity.class);
				  toEvent.putExtra("model", events.get(position).getModel());
				  toEvent.putExtra("lon", events.get(position).getLongitude());
				  toEvent.putExtra("location", events.get(position).getLocation());
				  toEvent.putExtra("society", events.get(position).getSociety());
				  toEvent.putExtra("lat", events.get(position).getLatitude());
				  toEvent.putExtra("description", events.get(position).getDescription());
				  toEvent.putExtra("name", events.get(position).getTitle());
				  toEvent.putExtra("pk", events.get(position).getPk());
				  toEvent.putExtra("start", events.get(position).getDateStart());
				  toEvent.putExtra("end", events.get(position).getDateEnd());
				  toEvent.putExtra("startDate", events.get(position).getStartDate());
				  toEvent.putExtra("startTime", events.get(position).getStartTime());
				  
				  startActivity(toEvent);
			  }
		  	});
	  	} catch (JSONException e) {
	  		Toast exception = Toast.makeText(getApplicationContext(), "JSON"+e.getMessage(), 100000);
	  		exception.show();
	  	} catch (Exception e) {
	  		Toast exception = Toast.makeText(getApplicationContext(), "Exception", Toast.LENGTH_SHORT);
	  		exception.show();
	  	}
	  }
	

	String[] requestEventsFromServer(String username) throws JSONException, Exception{
		String urlString = "http://intr.ep.io/events/user.json?username=dp1e10";
		//String urlString = "http://intr.ep.io/blogs/user.json?username="+username;
		String str = null;
		JSONArray result = null;
	    //JSONObject result = null;
		
		URL url;
		try {
			url = new URL(urlString);
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
			str = in.readLine();
			in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
			Toast connectionFailed = Toast.makeText(getApplicationContext(), "Connection failed!", Toast.LENGTH_SHORT);
			connectionFailed.show();
		}
	   	
		result = new JSONArray(str);
		String[] s = new String[result.length()];
		events = new ArrayList<EventEntry>();
		
		for(int i=0;i<result.length();i++){
			EventEntry temp = new EventEntry();
			temp.setDateEnd( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("end") );
			temp.setDateStart( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("start") );
			temp.setDescription( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("description") );
			temp.setLatitude( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("lat") );
			temp.setLocation( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("location") );
			temp.setLongitude( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("lon") );
			temp.setModel( ((JSONObject)result.get(i)).getString("model") );
			temp.setPk(((JSONObject)result.get(i)).getInt("pk"));
			temp.setSociety( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("society") );
			temp.setTitle( ((JSONObject)((JSONObject)result.get(i)).get("fields")).getString("name") );
			events.add(temp);		
		}
		
		Collections.sort(events);
		for(int i=0;i<events.size();i++){
			s[i] = events.get(i).getDateAndTitle();
		}
		return s;
	}
	
	//Menu stuff
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.refresh_menu:
	    	Toast toast = Toast.makeText(getApplicationContext(), "Refresh taking place", Toast.LENGTH_SHORT);
	        toast.show();
	        return true;
	    case R.id.logout_menu:
	    	Toast toast2 = Toast.makeText(getApplicationContext(), "Logging out", Toast.LENGTH_SHORT);
	        toast2.show();
	        
	        //remove authentication data
	        SharedPreferences.Editor editor = getSharedPreferences("PREF", 0).edit();
			editor.putBoolean("Authenticated", false);
			editor.putString("Username", "");
			editor.putString("Password", "");
			editor.commit();
			
			Intent toHome = new Intent(EventActivity.this, IntrActivity.class);
			startActivity(toHome);
	        return true;  
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
}
